package com.yuan.yblog.security.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 自定义加密
 */
@Component
public class CustomPasswordEncoder implements PasswordEncoder {

    //todo: 将md5加密方式迁移到BCryptPasswordEncoder
    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * 加密
     * @param rawPassword 原始密码
     * @return 密文
     */
    @Override
    public String encode(CharSequence rawPassword) {
        return SecureUtil.md5(rawPassword.toString());
    }

    /**
     * 密码匹配
     * @param rawPassword the raw password to encode and match
     * @param encodedPassword the encoded password from storage to compare with
     * @return true表示匹配成功
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return StrUtil.equals(encode(rawPassword),encodedPassword);
    }
}
